package cbir;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.*;

import javax.imageio.*;

import com.mortennobel.imagescaling.ResampleOp;

public class ScaleJPG {
	
	private static final int maxX_THUMB = 400;
	
	  public static void scale(String imgPath, String thumbPath, String filename, String thumbname)throws IOException {
		  
		  BufferedImage input = ImageIO.read(new File(imgPath+filename));
		  int altezza = 0, larghezza = 0;
		  
		  if(input.getHeight() < maxX_THUMB && input.getWidth() < maxX_THUMB)
		  {
			  altezza = input.getHeight();
			  larghezza = input.getWidth();
		  }
		  else if(input.getHeight() > input.getWidth())
		  {
			  larghezza = maxX_THUMB * input.getWidth() / input.getHeight();
			  altezza = maxX_THUMB;
		  }else if(input.getHeight() < input.getWidth())
		  {
			  altezza = maxX_THUMB * input.getHeight() / input.getWidth();
			  larghezza = maxX_THUMB;
		  }else
		  {
			  larghezza = maxX_THUMB;
			  altezza = maxX_THUMB;
		  }
		  
		  String ext = filename.substring(filename.lastIndexOf(".")+1, filename.length());
		  
		  if(ext.compareTo("png") != 0 && ext.compareTo("PNG") != 0 && ext.compareTo("gif") != 0 && ext.compareTo("GIF") != 0){	//nè png nè gif
			  ResampleOp  resampleOp = new ResampleOp (larghezza,altezza);
			  BufferedImage output = resampleOp.filter(input, null);
			  ImageIO.write(output,ext,new File(thumbPath+thumbname));
		  }else{
			  BufferedImage output= new BufferedImage(larghezza, altezza, BufferedImage.TYPE_INT_RGB);
			  Graphics2D g = output.createGraphics();
			  AffineTransform at =
				  AffineTransform.getScaleInstance((double)larghezza/input.getWidth(),(double)altezza/input.getHeight());
			  g.drawRenderedImage(input,at);
			  ImageIO.write(output,"jpg",new File(thumbPath+thumbname));
		  }
		  
		  // versione barbara di scaling (però è appena più veloce =) ) 
//		  BufferedImage output= new BufferedImage(larghezza, altezza, BufferedImage.TYPE_INT_RGB);
//		  
//		  Graphics2D g = output.createGraphics();
//		  AffineTransform at =
//			  AffineTransform.getScaleInstance((double)larghezza/input.getWidth(),(double)altezza/input.getHeight());
//		  g.drawRenderedImage(input,at);
//		  ImageIO.write(output,"JPG",new File(dest));
	  }

}